package cn.enjoy.dynamic.datasource.controller;

import cn.enjoy.dynamic.datasource.annotation.DataSource;
import cn.enjoy.dynamic.datasource.config.DynamicContextHolder;
import cn.enjoy.dynamic.datasource.service.IUserService;
import cn.enjoy.entity.User;
import cn.enjoy.dynamic.datasource.prop.DataSourceProperties;
import cn.enjoy.tool.api.R;
import cn.enjoy.dynamic.datasource.utils.DataSourceUtil;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLException;

/**
 * @author K
 * @date 2020/12/14 16:24
 */
@RestController
@AllArgsConstructor
public class DataSourceController {

    private IUserService userService;


    @GetMapping("/getUser")
    public R getUser(Long id) {
        User user = userService.getById(id);
        return R.data(user);
    }

    @DataSource("slave1")
    @GetMapping("/getUserBySlave1")
    public R getUserBySlave1(Long id) {
        User user = userService.getById(id);
        return R.data(user);
    }

    @DataSource("slave2")
    @GetMapping("/getUserBySlave2")
    public R getUserBySlave2(Long id) {
        User user = userService.getById(id);
        return R.data(user);
    }

    /**
     * 实际上不允许动态添加数据源
     */
    @PostMapping("/addDatasource")
    public R<User> addDatasource(DataSourceProperties dataSourceProperties, @RequestParam String alias, @RequestParam Long id) throws SQLException {
        // 添加
        boolean success = DataSourceUtil.addDataSource(alias, dataSourceProperties);
        // 刷新
        DataSourceUtil.flushDataSource();
        // 设置
        DynamicContextHolder.push(alias);

        User user = userService.getById(id);
        R<User> data = R.data(user);
        if (!success) {
            data.setMsg("数据库名称已存在，使用原有的数据源 " + alias);
        }
        return data;
    }

}
